(function (win, doc) {
	var defaultParams = {
		colors: ['#eb125f', '#6eff8a', '#6386ff', '#f9f383'],
		maxCount: 30 // 点击一次出现多少个小球
	}

	class ColorBall {
		constructor(params) {
			this.params = Object.assign({}, defaultParams, params);
		}
		// 随机获取球的颜色
		getColorRandom(arr) {
			return arr[Math.floor(Math.random()*arr.length)];
		}
		clear(balls) {
			setTimeout(function() {
				for(let  i=0; i< balls.length; i++){
					doc.body.removeChild(balls[i])
				}	
			}, 1000);
			
		}
		run(ball) {
			// 随机定义了x y的坐标
			var randomXFlag = Math.random() > 0.5
			var randomYFlag = Math.random() > 0.5

			var randomX = parseInt(Math.random() * 200);
			var randomY = parseInt(Math.random() * 200);
			if (randomXFlag) {
					randomX = randomX * -1;
			}
			if (randomYFlag) {
					randomY = randomY * -1
			}
			let transform = 'translate3d('+randomX+'px,' + randomY + 'px, 0) scale(0)';
			ball.style.transform = transform;
		}

		fly(x, y) {
			var ballElements = []
			var fragment = document.createDocumentFragment()
			var ballNum = this.params.maxCount; // 点击一次出现多少个圆球 默认是30

			for(let i= 0; i<ballNum; i++) {
				var ball = doc.createElement('i');
				ball.style.left = (x) + 'px';
				ball.style.top = (y) + 'px';
				// 随机获取颜色
				ball.style.backgroundColor = this.getColorRandom(this.params.colors);
				fragment.appendChild(ball);
				ballElements.push(ball)
			}
			doc.body.appendChild(fragment);
			// 延迟删除
			this.clear(ballElements)
			// 执行动画
			requestAnimationFrame(() => {
				for(var i=0; i<ballElements.length; i++){
					this.run(ballElements[i])
				}	
			}, 10)
		}
	}
	//兼容CommonJs规范 
	if (typeof module !== 'undefined' && module.exports) {
		module.exports = ColorBall;
	};
	//兼容AMD/CMD规范
	if (typeof define === 'function') define(function() { 
		return ColorBall; 
	});
	//注册全局变量，兼容直接使用script标签引入插件
	win.ColorBall = ColorBall;
 })(window, document)

